#!/usr/bin/python3
import os.path
import random
import sys
from pathlib import Path
import subprocess
import platform
import concurrent.futures
import threading


# 执行metis和mqi
def executeCmd(cmd_str: list, verbose=False):
    # os.system(cmd_str)
    print(cmd_str)
    if platform.system() == 'Windows':
        process = subprocess.run(cmd_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        print(process.stdout)
    elif platform.system() == 'Linux':
        # os.system(cmd_str)
        process = subprocess.run(cmd_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
                                 shell=True)
        if verbose:
            print(process.stdout)
    else:
        print('Error!!!')


def runMetis(file, times):
    fileName = file + ".graph"
    input_path = os.path.join("..", "instance", fileName)
    metis_exe_path = os.path.join("..", "runtime", "gpmetis")
    mqi_exe_path = os.path.join("..", "runtime", "mqi")
    seed_list = random.sample(range(1, 100000000), times)
    for id, seed in enumerate(seed_list):
        metis_cmd_str = f'{metis_exe_path} -seed={str(seed)} -objtype=vol {input_path} 2'
        # metis 优化
        executeCmd(metis_cmd_str)
        output = os.path.join("..", "instance", fileName + ".part.2")
        ans = []
        # 读取分区文件
        with open(output, 'r') as rf:
            lines = rf.readlines()
            for i, line in enumerate(lines):
                part = int(line[0])
                if part == 1:
                    ans.append(i)
        # 写入到MQI_BKV里面
        file_path = Path(os.path.join("..", "MQI_BKV", file, file + "_result_" + str(id) + ".smat"))
        file_path.parent.mkdir(parents=True, exist_ok=True)# 确保目录存在
        with open(file_path, 'w') as wf:
            wf.write(str(len(ans)) + "\n")
            for v in ans:
                wf.write(str(v) + "\n")
        # 调用mqi优化
        mqi_seed = random.randint(1, 100000000)
        mqi_cmd_str = f'{mqi_exe_path} {file} {str(id)} {str(mqi_seed)}'
        executeCmd(mqi_cmd_str,True)


def runMetisAndMqi(file, output, metis_cmd_str, mqi_cmd_str):
    # 执行metis
    executeCmd(metis_cmd_str)
    ans = []
    # 读取分区文件
    with open(output, 'r') as rf:
        lines = rf.readlines()
        for i, line in enumerate(lines):
            part = int(line[0])
            if part == 1:
                ans.append(i)
    # 写入到MQI_BKV里面
    s = os.path.join("..", "MQI_BKV", file, file + "_result_" + str(id) + ".smat")
    with open(s, 'w') as wf:
        wf.write(str(len(ans)) + "\n")
        for v in ans:
            wf.write(str(v) + "\n")
    # 调用mqi优化
    executeCmd(mqi_cmd_str)


if __name__ == '__main__':
    file_path = sys.argv[1]  # xx.txt
    thread_count = int(sys.argv[2]) # 线程数
    print("case txt:",file_path,"线程数:",thread_count)
    # 读取输入
    test_case = []
    with open(file_path, 'r') as rf:
        lines = rf.readlines()
        for line in lines:
            line = line.strip()
            line_list = line.split(' ')
            test_case.append(line.split(' '))

    # 创建线程池
    with concurrent.futures.ThreadPoolExecutor(max_workers=thread_count) as executor:
        # 提交任务到线程池
        for line_list in test_case:
            file = line_list[0]
            times = int(line_list[1])
            print("file:",file,"times:",times)
            executor.submit(runMetis,file,times)
        # 等待所有任务完成
        executor.shutdown()
        print("over!")
